package com.lightman.gulimall.product.web;

import com.lightman.gulimall.product.entity.CategoryEntity;
import com.lightman.gulimall.product.service.CategoryService;
import com.lightman.gulimall.product.vo.CatelogTwoVo;
import org.redisson.api.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Controller
public class IndexController {

    @Autowired
    private RedissonClient redisson;

    @Resource
    private CategoryService categoryService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    // 跳转首页
    @GetMapping({"/", "/index.html"})
    public String indexPage(Model model) {

        //TODO 查出所有的一级分类
        List<CategoryEntity> categoryEntities = categoryService.getLevelOneCategorys();

        System.out.println(categoryEntities);
        // 默认转发
        model.addAttribute("categorys", categoryEntities);

//        public static final String DEFAULT_PREFIX = "classpath:/templates/";
//
//        public static final String DEFAULT_SUFFIX = ".html";

        return "index";
    }

    // index/catalog.json
    // index/catalog.json
    @ResponseBody
    @GetMapping("/index/catalog.json")
    public Map<String, List<CatelogTwoVo>> getCatalogJson(){
        Map<String, List<CatelogTwoVo>> map = categoryService.getCatalogJson();
        return map;
    }

    @ResponseBody
    @GetMapping("/hello")
    public String hello(){

        // 1、获取锁, 只要名字一样就是同一把锁,不用担心业务时间长,锁自动过期,
        RLock lock = redisson.getLock("my-lock");

        // 2、加锁(默认时间30s)
        lock.lock(3000, TimeUnit.SECONDS); // 阻塞式等待 自定义解锁时间,一定要大于业务时间,她不会帮我们自动续期
        // 锁的字段续期, 如果业务超长,运行期间自动给锁续上30s
        // 加锁的业务只要运行完成,就不会给当前业务续期,即使不手动解锁,默认早30s后自动删除

        /**
         * 1、如果我们传递了超时时间,就发送给redis执行脚本,进行占锁, 默认就是我们的潮湿时间
         * 2、如果我们未指定超时时间,就使用(看门狗时间)
         *      只要占锁成功,就会启动一个定时任务,【重新给锁设置过期时间,新的过期时间就是看嘛狗的默认时间】
         *      1/3 看么狗时间,续期
         */

        // 最佳 实战 lock.lock(3000, TimeUnit.SECONDS);
        try {
            System.out.println("加锁成功,执行业务............."+ Thread.currentThread().getId());
            Thread.sleep(3000);
        }catch (Exception e){

        }finally {
            // 3解锁
            lock.unlock();
            System.out.println("释放锁...."+ Thread.currentThread().getId());
        }

        return "hello";
    }


    /**
     * 保证一定能够读到最新数据, 修改期间,写锁是一个排他锁(互斥锁)
     *
     * 写锁没释放读锁必须等待
     * 读+读; 相当于 无锁,并发读,只会在redis中记录,所有当前的读锁,他们都会同时加锁成功
     * 写+读 等待写释放
     * 读+写 有读锁,写也必须等待
     *  只要有写的存在,都必须等待
     */
    @ResponseBody
    @GetMapping(value = "/write")
    public String writeValue(){

        RReadWriteLock lock = redisson.getReadWriteLock("rw-lock");
        String s = null;
        RLock rLock = null;
        try {
            // 1、改数据加写锁,读数据加读锁
            rLock = lock.writeLock();
            rLock.lock();
            System.out.println("写锁加锁成功..."+ Thread.currentThread().getId());
            s = UUID.randomUUID().toString();
            Thread.sleep(30000);
            redisTemplate.opsForValue().set("writeValue", s);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            rLock.unlock();
            System.out.println("写锁释放..."+ Thread.currentThread().getId() );
        }

        return s;
    }

    @ResponseBody
    @GetMapping(value = "/read")
    public String readValue(){

        RReadWriteLock lock = redisson.getReadWriteLock("rw-lock");
        String s = null;

        // 加读锁
        RLock rLock = lock.readLock();
        try {
            rLock.lock();
            System.out.println("读锁加锁成功..."+Thread.currentThread().getId());
            s = redisTemplate.opsForValue().get("writeValue");
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            rLock.unlock();
            System.out.println("读锁释放成功..."+Thread.currentThread().getId());
        }

        return s;
    }


    /**
     * 车库停车
     * 3车位
     * 信号量也可以用作分布式限流
     */
    @ResponseBody
    @GetMapping("/park")
    public String parks() throws InterruptedException{
        RSemaphore park = redisson.getSemaphore("park");
        boolean b = park.tryAcquire();




        return "ok ===>" + b;
    }

    @ResponseBody
    @GetMapping("/go")
    public String gos() throws InterruptedException{
        RSemaphore park = redisson.getSemaphore("park");
        park.release(); // 释放一个车位

        return "ok";
    }

    /**
     *  放假锁门
     *  假设有5个班, 5个班人都走了
     *  就可以锁门了
     */
    @ResponseBody
    @GetMapping(value = "/lockDoor")
    public String lockDoor() throws InterruptedException{

        RCountDownLatch door = redisson.getCountDownLatch("door");
        door.trySetCount(5); // 设置班级数

        door.await(); //等待锁执行完毕,执行代码

        return "放假了..........";
    }

    @ResponseBody
    @GetMapping(value = "/gogogo/{id}")
    public String gogogo(@PathVariable("id") Long id){

        RCountDownLatch door = redisson.getCountDownLatch("door");
        door.countDown(); // 计数减一

        return id+"班的人走了....";

    }
}
